Page({
  data: {
    phone: '',
    code: '',
    codeText: '获取验证码',
    timer: null,
    countdown: 60,
    canGetCode: true
  },

  // 手机号输入
  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  // 验证码输入
  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    });
  },

  // 获取验证码
  getCode() {
    if (!this.data.canGetCode) return;
    
    const phone = this.data.phone;
    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    // 开始倒计时
    this.setData({
      canGetCode: false,
      codeText: this.data.countdown + 's',
      timer: setInterval(() => {
        if (this.data.countdown <= 1) {
          clearInterval(this.data.timer);
          this.setData({
            codeText: '获取验证码',
            timer: null,
            countdown: 60,
            canGetCode: true
          });
          return;
        }
        this.setData({
          countdown: this.data.countdown - 1,
          codeText: (this.data.countdown - 1) + 's'
        });
      }, 1000)
    });

    // 模拟发送验证码
    wx.showToast({
      title: '验证码已发送',
      icon: 'success'
    });
  },

  // 绑定手机号
  bindPhone() {
    const { phone, code } = this.data;
    
    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!code) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '绑定中...'
    });

    // 模拟绑定手机号
    setTimeout(() => {
      wx.hideLoading();
      
      // 更新本地存储的用户信息
      const userInfo = wx.getStorageSync('userInfo') || {};
      userInfo.phoneNumber = phone;
      userInfo.hasPhone = true;
      wx.setStorageSync('userInfo', userInfo);
      
      wx.showToast({
        title: '绑定成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            // 跳转到设置密码页面
            wx.navigateTo({
              url: '/pages/my/setPassword/setPassword'
            });
          }, 2000);
        }
      });
    }, 1000);
  },

  onUnload() {
    // 清除定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  }
}); 